<template>
    <div class="user-edit-container">
        <!-- header区域 -->
        <van-nav-bar title="编辑资料" left-arrow  @click-left="onClickLeft" />

        <!-- 编辑区域 -->
        <van-cell-group class="action-card">
            <van-cell title="头像"  is-link class="photo">
                <template #default>
                    <img :src="$store.state.user.photo" alt="" class="avatar" @click="imgClickFn">
                    <!-- file 选择框 -->
                    <input
                        type="file"
                        ref="iptFileRef"
                        v-show="false"
                        accept="image/*"
                        @change="onFileChange"
                        />
                </template>
            </van-cell>
            <van-cell title="名称" :value="$store.state.user.name" is-link @click="updateName" ></van-cell>
            <van-cell title="性别" :value="userObj.gender===0?'男':'女'" is-link ></van-cell>
            <van-cell title="生日" :value="userObj.birthday" is-link @click="updateBirthday"></van-cell>
        </van-cell-group>

        <!-- 修改姓名对话框 -->
        <van-dialog v-model="showNameDialog" title="修改用户名" show-cancel-button
        :before-close="beforeCloseFn"
        >
            <van-field v-model="username"  placeholder="请输入用户名" v-fofo/>
        </van-dialog>

        <!-- 生日的时间选择 -->
        <van-popup v-model="dateTimePickerShow" position="bottom" round >
            <van-datetime-picker
            v-model="currentDate"
            type="date"
            title="选择年月日"
            :min-date="minDate"
            :max-date="maxDate"
            @confirm="dateConfirm"
            @cancel="dateCancel"
            />
        </van-popup>

    </div>
</template>

<script>
import { getUserInfoAPI, updatePhotoAPI, updateUserProfileAPI } from '@/api'
import { Notify } from 'vant'
import { formatDate } from '@/utils/date'
import { mapMutations } from 'vuex'
export default {
  data () {
    return {
      // 用户信息
      userObj: {},
      // 显示修改姓名的对话框
      showNameDialog: false,
      // 时间弹出层显示
      dateTimePickerShow: false,
      // 用户名
      username: '',
      minDate: new Date(1980, 0, 1),
      maxDate: new Date(),
      currentDate: new Date(1980, 0, 1)
    }
  },
  created () {
    this.getUserInfo()
  },
  methods: {
    ...mapMutations(['SET_USERPHOTO', 'SET_USERNAME']),
    // 获取用户信息
    async getUserInfo () {
      // 获取用户信息
      const { data: res } = await getUserInfoAPI()
      //   console.log(res)
      this.userObj = res.data
      this.username = res.data.name
    },

    // 返回箭头的点击事件
    onClickLeft () {
      this.$router.back()
    },

    // 图片的点击事件
    imgClickFn () {
      // 调用file 的点击事件
      this.$refs.iptFileRef.click()
    },

    // file选择框的点击事件
    async onFileChange (e) {
      // 如果用户点击了取消上传图片，直接return
      if (e.target.files.length === 0) return
      // 创建FormData表单对象
      const fd = new FormData()
      // 必须为photo
      fd.append('photo', e.target.files[0])
      const { data: res } = await updatePhotoAPI(fd)
      //   console.log(res)
      // 替换头像 没有重新请求刷新 效果会更好
      this.SET_USERPHOTO(res.data.photo)
      Notify({
        type: 'success',
        message: '上传头像成功'
      })
    },

    // 修改名字显示对话框
    updateName () {
      this.showNameDialog = true
    },

    // 对话框的关闭事件——修改用户名
    async beforeCloseFn (action, done) {
      if (action === 'confirm') {
        // 点击确定
        // 准备正则
        const reg = /^[A-Za-z0-9\u4e00-\u9fa5]{1,7}$/
        if (reg.test(this.username)) {
        //   验证成功，调用接口进行修改
          await updateUserProfileAPI({
            name: this.username
          })
          this.userObj.name = this.username
          this.SET_USERNAME(this.username)
          done()
        } else {
          Notify({
            type: 'warning',
            message: '用户名只能包含1到7位的字母数字和中文'
          })
          this.username = this.userObj.name
          done()
        }
      } else {
        done()
      }
    },

    // 编辑生日——弹出日期对话框
    updateBirthday () {
      this.dateTimePickerShow = true
      this.currentDate = new Date(this.userObj.birthday)
    },

    // 点击时间的取消按钮
    dateCancel () {
      this.dateTimePickerShow = false
    },

    // 点击时间的确认按钮
    async dateConfirm () {
      console.log(formatDate(this.currentDate))
      // 发起请求，修改生日日期
      await updateUserProfileAPI({
        birthday: formatDate(this.currentDate)
      })
      this.dateTimePickerShow = false
      // 页面同步
      this.userObj.birthday = formatDate(this.currentDate)
    }

  }
}
</script>

<style lang="less" scoped>
.van-nav-bar {
    background-color: #007bff;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
}
 /deep/.van-nav-bar__title{
  color: #fff;
}
/deep/ .van-icon-arrow-left:before{
  color:#fff;
}
.user-edit-container{
    padding-top: 46px;
    .avatar{
        width: 50px;
        height: 50px;
        border-radius: 50%;
    }
}

</style>
